//
//  XLGestureLockVC.m
//  industry
//
//  Created by xl on 2020/12/30.
//  Copyright © 2020 Haier. All rights reserved.
//

#import "XLGestureLockVC.h"
#import "XLGestureLockView.h"
#import "XLUserDefaults.h"

@interface XLGestureLockVC ()<XLGestureLockDelegate>

@property (nonatomic, strong) XLLabel *titleLB;
@property (nonatomic, strong) XLButton *retryBtn;
@property (nonatomic, strong) XLGestureLockView *lockView;
@property (nonatomic, strong) XLButton *sureBtn;

@property (nonatomic, copy) NSString *lastPS;
@property (nonatomic, copy) NSString *currentPS;

@property (nonatomic, assign) NSInteger nextStep;//如果是设置密码 1第一次设置密码 2再次确认密码；如果是更换密码 1是校验密码  2.设置新密码  3.再次确认密码

@end

@implementation XLGestureLockVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.nextStep = 1;
    [self buildView];
    if (self.type == XLGestureLockVCFromTypeSetting) {
        self.navigationItem.title = @"手势设置";
        _titleLB.text = @"请绘制新的手势";
    } else {
        self.navigationItem.title = @"修改手势设置";
        _titleLB.text = @"请绘制之前设置的手势";
    }
}

- (void)buildView {
    [self.view addSubview:self.titleLB];
    [self.view addSubview:self.retryBtn];
    [self.view addSubview:self.lockView];
    [self.view addSubview:self.sureBtn];
    
    [_titleLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(30);
        make.top.equalTo(self.view).offset(25);
    }];
    
    [_retryBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.titleLB.mas_right).offset(20);
        make.centerY.equalTo(self.titleLB);
    }];
    
    [_lockView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.top.equalTo(self.titleLB.mas_bottom).offset(10);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, SCREEN_WIDTH));
    }];
    
    [_sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.titleLB);
        make.top.equalTo(self.lockView.mas_bottom).offset(20);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH - 30*2, 45));
    }];
}

#pragma mark - UIButton
- (void)clickAgainDraw {
        if (self.type == XLGestureLockVCFromTypeSetting) {
            if (self.nextStep == 1) {//第一次输入数字密码
                self.lastPS = nil;
            } else {//第二次输入数字密码
                self.currentPS = nil;
            }
        } else {
            if (self.nextStep == 1) {
                self.lastPS = nil;
                self.currentPS = nil;
            } else if (self.nextStep == 2) {
                self.lastPS = nil;
            } else {
                self.currentPS = nil;
            }
        }
    [_lockView clearLockView];
    _titleLB.text = @"请重新输入";
}

- (void)clickSure {
    if (ISEmptyString(self.lastPS) || ISEmptyString(self.currentPS)) {
        [XLToast showErrorMessage:@"当前手势密码不合法！"];
        return;
    }
    
    if (![self.lastPS isEqualToString:self.currentPS]) {
        [XLToast showErrorMessage:@"前后手势不一致！"];
        return;
    }
    
    [XLToast showSuccessMessage:@"设置成功"];
    //存储合理密码
    [XLUserDefaults saveLastGesturePassword:self.currentPS];
    if (self.resultBlock) {
        self.resultBlock();
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - XLGestureLockDelegate
- (void)gestureLockView:(XLGestureLockView *)lockView drawRectFinished:(NSMutableString *)gesturePassword {
    if (gesturePassword.length < 4) {
        _titleLB.text = @"至少连接四个点，请重新输入";
        [self shakeAnimationForView:_titleLB];
        [lockView clearLockView];
        return;
    }
    XLLog(@"当前绘制密码%@", gesturePassword);
    
    if (self.type == XLGestureLockVCFromTypeSetting) {
        if (self.nextStep == 1) {//第一次输入数字密码
            _titleLB.text = @"请再次绘制手势";
            self.nextStep = 2;
            self.lastPS = gesturePassword;
            [lockView clearLockView];
        } else {//第二次输入数字密码
            self.currentPS = gesturePassword;
            [self autoCheckPS];
        }
    } else {
        NSString *savePS = [XLUserDefaults getLastGesturePassword];
        if (self.nextStep == 1) {//校验密码
            if ([savePS isEqualToString:gesturePassword]) {
                self.nextStep = 2;
                _titleLB.text = @"请绘制新的手势";
                [lockView clearLockView];
            } else {
                _titleLB.text = @"手势校验错误";
                [self shakeAnimationForView:_titleLB];
                [lockView clearLockView];
            }

        } else if (self.nextStep == 2) {
            _titleLB.text = @"请再次绘制手势";
            self.nextStep = 3;
            self.lastPS = gesturePassword;
            [lockView clearLockView];
        } else {
            self.currentPS = gesturePassword;
            [self autoCheckPS];
        }
    }
}

#pragma mark - Private
// 抖动动画
- (void)shakeAnimationForView:(UIView *)view {
    CALayer *viewLayer = view.layer;
    CGPoint position = viewLayer.position;
    CGPoint left = CGPointMake(position.x - 10, position.y);
    CGPoint right = CGPointMake(position.x + 10, position.y);
    
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    [animation setFromValue:[NSValue valueWithCGPoint:left]];
    [animation setToValue:[NSValue valueWithCGPoint:right]];
    [animation setAutoreverses:YES]; // 平滑结束
    [animation setDuration:0.08];
    [animation setRepeatCount:3];
    
    [viewLayer addAnimation:animation forKey:nil];
}

// 自动检查前后两次手势密码是否一致
- (void)autoCheckPS {
    // 如果查出不一致，就toast提示;并清除（相当于按了重新输入按钮）; 并晃动
    if (![self.lastPS isEqualToString:self.currentPS]) {
        [self clickAgainDraw];
        [XLToast showErrorMessage:@"前后手势不一致！"];
        _titleLB.text = @"前后手势不一致！请重新输入";
        [self shakeAnimationForView:_titleLB];
    } else {
        _titleLB.text = @"请点击确认按钮";
    }
}

#pragma mark - Setter/getter
- (XLLabel *)titleLB {
    if (!_titleLB) {
        _titleLB = [XLLabel new];
        _titleLB.font = [UIFont fontOfPingFangSCSemiboldWithSize:15];
        _titleLB.textColor = [UIColor blackFontColor];
        _titleLB.text = @"设置手势密码";
    }
    return _titleLB;
}

- (XLButton *)retryBtn {
    if (!_retryBtn) {
        _retryBtn = [XLButton new];
        _retryBtn.titleLabel.font = [UIFont fontOfPingFangSCSemiboldWithSize:15];
        [_retryBtn setTitleColor:[UIColor blueBgColor] forState:UIControlStateNormal];
        [_retryBtn setTitle:@"重新绘制手势" forState:UIControlStateNormal];
        [_retryBtn addTarget:self action:@selector(clickAgainDraw) forControlEvents:UIControlEventTouchUpInside];
    }
    return _retryBtn;
}

- (XLGestureLockView *)lockView {
    if (!_lockView) {
        _lockView = [[XLGestureLockView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH)];
        _lockView.backgroundColor = [UIColor whiteColor];
        _lockView.delegate = self;
    }
    return _lockView;
}

- (XLButton *)sureBtn {
    if (!_sureBtn) {
        _sureBtn = [XLButton new];
        _sureBtn.backgroundColor = [UIColor blueBgColor];
        _sureBtn.layer.cornerRadius = 22.5;
        _sureBtn.layer.masksToBounds = YES;
        _sureBtn.titleLabel.font = [UIFont fontOfPingFangSCSemiboldWithSize:16];
        [_sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_sureBtn setTitle:@"确定" forState:UIControlStateNormal];
        [_sureBtn addTarget:self action:@selector(clickSure) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sureBtn;
}

@end
